import React, { PropTypes, Component } from 'react'
// import {Editor, EditorState, RichUtils} from 'draft-js'
import RichText from './RichText'

import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import InputWithLabel from './InputWithLabel'
import CheckboxInput from './CheckboxInput'
import TextInput from './TextInput'
import FileInput from './FileInput'
import ImageWithState from './ImageWithState'

import TextareaInput from './TextareaInput'
import SelectInput from './SelectInput'
import Layers from './Layers'

import Table from './Table'
import NavLink from './NavLink'
import style from './addStore.css'

import { myAjax, ROOTURL, ROOTURL_MALL } from '../publicAPI/publicAPI'

class MallProductsEditor extends Component {
	constructor (props, context) {
	    super(props, context)
	    console.log("初始化");

	    this.state = {
	    	previewImgFiles: [],
	    	previewImgUrl: [],
	    	imgHash: [],
	    	icon: '',
	    	iconFile : null,
	    	iconPreview: '',
	    	iconHasChanged : false,

	        hasBeenMounted: false,
	        delete: false,
	        deleteId: -1,
	        status:1,//2修改，1新增
	        select_show: "none",
	        select_show1: "none",
	        select_show2: "none",
	        select_show3: "none",
	        select_show4: "none",
	        select_show5: "none",
	        select_show6: "none",
	        select_show7: "none",
	        select_show8: "none",
	        select_show9: "none",
	        typeBelong:'',
	        typeSelectId:-1,
	        errorM: "",
	        errorM1: "",

	        productName:'',
	        price:'',
	        tag:'',
	        detailUrl:'',
	        typeData:[],

	        stock:'',
	        initPrice:'',
	        checkbox1:false,
	        checkbox2:false,
	        restrictCount:1,

	        disabled:false,
	        submitBtn:'block',
	        modifyBtn:'none',
	        deleteBtn:'none',

	        //优惠券
	        gifts:[],
	        // gifts1:{},
	        // gifts2:{},
	        // gifts3:{},
	        typeDataOption1:[],//优惠券1商品类型（数组）
	        proDataOption1:[],//优惠券1商品名（数组）
	        giftDataOption1:[],//优惠券1优惠类型（数组）

	        typeDataOption2:[],//优惠券2商品类型（数组）
	        proDataOption2:[],//优惠券2商品名（数组）
	        giftDataOption2:[],//优惠券1优惠类型（数组）

	        typeDataOption3:[],//优惠券3商品类型（数组）
	        proDataOption3:[],//优惠券3商品名（数组）
	        giftDataOption3:[],//优惠券1优惠类型（数组）

	        giftItem1_productT:'',
	        giftItem1_product:'',
	        giftItem1_productId:'',
	        giftItem1_type:'',
	        giftItem1_typeId:'',
	        giftItem1_count:0,

	        giftItem2_productT:'',
	        giftItem2_product:'',
          giftItem2_productId:'',
	        giftItem2_type:'',
	        giftItem2_typeId:'',
	        giftItem2_count:0,

	        giftItem3_productT:'',
	        giftItem3_product:'',
          giftItem3_productId:'',
	        giftItem3_type:'',
	        giftItem3_typeId:'',
	        giftItem3_count:0,

					zitiORwuliu: '', //自提or物流
					select_ztORwl: 'none', // 自提or物流下拉

					// 提成比例

					ratio: 0.0,
					minValue: 0.0,
					maxValue: 0.0


	    } ;// 初始化状态
	    this.handleImgUpload.bind(this);

	    //获取商品分类
	    var URL = ROOTURL_MALL +'kabuy/category/search.api';
      var _this = this ;
      fetch(URL, {
          method : 'POST',
          mode: 'cors',
          body: JSON.stringify({})
      }).then(res=>{
          if(res.ok){
              res.json().then(data=>{
                  for(var i=0;i<data.length;i++){
                  	if(data[i].dd == false){
                  		_this.state.typeData.push(<li data-id={data[i].id} onClick={(e) => this.inputTClick(e)}>{data[i].name}</li>)
                  	}
                  }
                  for(var i=0;i<data.length;i++){
                  	if(data[i].dd == false){
                  		_this.state.typeDataOption1.push(<li data-id={data[i].id} onClick={(e) => this.inputTClick1(e)}>{data[i].name}</li>)
                  		_this.state.typeDataOption2.push(<li data-id={data[i].id} onClick={(e) => this.inputTClick2(e)}>{data[i].name}</li>)
                  		_this.state.typeDataOption3.push(<li data-id={data[i].id} onClick={(e) => this.inputTClick3(e)}>{data[i].name}</li>)
                  	}
                  }
              })
          }
      })

      //获取优惠券类型
	    var URL = ROOTURL_MALL +'kabuy/coupon/type/search.api';
      var _this = this ;
      fetch(URL, {
          method : 'POST',
          mode: 'cors',
          body: JSON.stringify({})
      }).then(res=>{
          if(res.ok){
              res.json().then(data=>{
                  for(var i=0;i<data.length;i++){
                  	if(data[i].stValid){
                  		_this.state.giftDataOption1.push(<li data-id={data[i].id} onClick={(e) => {e.preventDefault;this.inputTClick1_type(e)}}>{data[i].dname}</li>)
                  		_this.state.giftDataOption2.push(<li data-id={data[i].id} onClick={(e) => {e.preventDefault;this.inputTClick2_type(e)}}>{data[i].dname}</li>)
                  		_this.state.giftDataOption3.push(<li data-id={data[i].id} onClick={(e) => {e.preventDefault;this.inputTClick3_type(e)}}>{data[i].dname}</li>)
                  	}

                  }
              })
          }
      })
	}

	componentWillMount() {
	     console.log("将安装");

	     if (this.props.params.id != undefined) {
	         //    根据参数获取数据

	         console.log('-----',this.props.params.id);
	         this.setState({
	         	disabled:true,
	           submitBtn:'none',
	           modifyBtn:'block',
	           deleteBtn:'block',

	         });

	         if (!this.state.hasBeenMounted && this.props.params.id){
	             console.log('set finished');
	             this.handleGetInfo();
	         }
	     }else{
	         this.setState({
	         	disabled:false,
	           submitBtn:'block',
	           modifyBtn:'none',
	           deleteBtn:'none',

	         });
	     }
	}

	handleImgUpload(files) {
	    var fileUrl = [];
	    var _this = this;
	    files.map(file=> {
	        var freader = new FileReader();
	        freader.readAsDataURL(file);
	        freader.onload = function (e) {
	            fileUrl.push({src: e.target.result});

	            //因异步操作存在多次渲染，待修改
	            _this.setState(Object.assign({}, this.state, {
	                previewImgFiles: files,
	                previewImgUrl: fileUrl
	            }));
	        };

	    });

	}

    handleIconUpload(files) {
        var _this = this;
        this.setState({iconHasChanged:true});
        files.map(file=> {
            var freader = new FileReader();
            freader.readAsDataURL(file);
            freader.onload = function (e) {
                _this.setState(Object.assign({}, this.state, {
                    iconPreview: e.target.result,
                    iconFile : file
                }));
            };

        });

    }

	handleIconSave(callback){
	    var _this = this;
	    const imgfile_url = this.state.iconPreview;
	    const imgfile = this.state.iconFile;

	    if(!imgfile || !imgfile_url){
	        callback();
	        return;
	    }
	    var img = new Image();
	    img.src = imgfile_url;
	    const width = img.width;
	    const height = img.height;
	    var fd = new FormData();
	    var xhr = new XMLHttpRequest();
	    xhr.open("POST", ROOTURL + "asset/images/upload.api?width=" + width + "&height=" + height + "&noShrink=" + true);

	    fd.append("file", imgfile);
	    xhr.send(fd);
	    xhr.onload = function (data) {
	        var status = data.currentTarget.status;
	        if (status == 200) {
	            var res_hashed = JSON.parse(data.currentTarget.response).hashed;
	            _this.setState({
	                icon: res_hashed
	            });
	            callback();
	        }
	        else {
	            console.log('图标保存失败:'+data);
	            callback();
	        }
	    }
	}

	handlesave() {
	    var _this = this;
	    const imgfile_url = this.state.previewImgUrl;
	    const imgfiles = this.state.previewImgFiles;
	    var j = 0;
	    for (var i = 0; i < imgfiles.length; i++) {
	        var img = new Image();
	        img.src = imgfile_url[i].src;
	        const width = img.width;
	        const height = img.height;
	        console.log(width, height);
	        var fd = new FormData();
	        var xhr = new XMLHttpRequest();
	        xhr.open("POST", ROOTURL + "asset/images/upload.api?width=" + width + "&height=" + height + "&noShrink=" + true);
	        var f = imgfiles[i];
	        fd.append("file", f);
	        xhr.send(fd);
	        xhr.onload = function (data) {
	            var status = data.currentTarget.status;
	            if (status == 200) {
	                var imageList = _this.state.previewImgUrl;
	                var imgData = _this.state.previewImgUrl[j];
	                imageList[j] = imgData;
	                imgData.msg = '保存成功';
	                _this.setState({
	                    previewImgUrl: imageList
	                });
	                j++;
	                var res = data.currentTarget.response;
	                var res_json = JSON.parse(res);
	                var res_hashed = res_json.hashed;
	                _this.setState({
	                    imgHash: _this.state.imgHash.concat(res_hashed)
	                });
	                if (j == imgfiles.length) {
	                    _this.handleIconSave(_this.handleSubmit.bind(_this))
	                }
	            }
	            else {
	                var imageList = _this.state.previewImgUrl;
	                var imgData = _this.state.previewImgUrl[j];
	                imageList[j] = imgData;
	                imgData.msg = '保存失败';
	                _this.setState({
	                    previewImgUrl: imageList
	                });
	                j++;

	                if (j == imgfiles.length) {
	                    _this.handleIconSave(_this.handleSubmit.bind(_this))
	                }
	            }
	        }
	    }
	    if (!imgfiles.length) {
	        _this.handleIconSave(_this.handleSubmit.bind(_this))
	    }
	}

	getOptions(data){
	    var options = [];
	    options.push(data.map((e,index)=><option key={index} value={e}>{e}</option>));
	    return options;
	}

	inputFocus() {
	    this.setState({select_show: "block"})
	}
	inputFocus1() {
	    this.setState({select_show1: "block"})
	}
	inputFocus2() {
	    this.setState({select_show2: "block"})
	}
	inputFocus3() {
	    this.setState({select_show3: "block"})
	}
	inputFocus4() {
	    this.setState({select_show4: "block"})
	}
	inputFocus5() {
	    this.setState({select_show5: "block"})
	}
	inputFocus6() {
	    this.setState({select_show6: "block"})
	}
	inputFocus7() {
	    this.setState({select_show7: "block"})
	}
	inputFocus8() {
	    this.setState({select_show8: "block"})
	}
	inputFocus9() {
	    this.setState({select_show9: "block"})
	}
	inputFocusZTORUL() {
		 this.setState({select_ztORwl: "block"})
	}


	inputTClick(e) {
	    const selectValue = e.target.innerText
	    console.warn(e.target.getAttribute('data-id'));
	    this.setState({
	      typeSelectId: e.target.getAttribute('data-id')
	    })
	    this.setState({select_show: "none", typeBelong: selectValue})
	}
	inputTClick1(e) {
	    const selectValue = e.target.innerText
	    console.warn(e.target.getAttribute('data-id'));
	    this.setState({
	      optionSelectId1: e.target.getAttribute('data-id')
	    })
	    this.setState({select_show1: "none", giftItem1_productT: selectValue, giftItem1_product:'', giftItem1_type:'', select_show4: "none", select_show7: "none", select_show5: "none", select_show8: "none", select_show6: "none", select_show9: "none"})

	    var URL = ROOTURL_MALL +'kabuy/item/search.api';
    	var _this = this ;
      fetch(URL, {
          method : 'POST',
          mode: 'cors',
          body: JSON.stringify({
          	"where":{
          	   categoryId: [
          	        ["eq",e.target.getAttribute('data-id')]
          	    ],
          	  },
          })
      }).then(res=>{
          if(res.ok){
              res.json().then(data=>{
              		_this.state.proDataOption1=[];
                  for(var k=0; k<data.length; k++){
                  	if(!(data[k].dd)){
                  		_this.state.proDataOption1.push(<li data-id={data[k].id} onClick={(e) => this.inputTClick1_pro(e)}>{data[k].name}</li>)
                  	}
                  }
              })
          }
      })
	}
	inputTClick2(e) {
	    const selectValue = e.target.innerText
	    console.warn(e.target.getAttribute('data-id'));
	    this.setState({
	      optionSelectId2: e.target.getAttribute('data-id')
	    })
	    this.setState({select_show2: "none", giftItem2_productT: selectValue, giftItem2_product:'', giftItem2_type:'', select_show5: "none", select_show8: "none", select_show4: "none", select_show7: "none", select_show6: "none", select_show9: "none" })

	    var URL = ROOTURL_MALL +'kabuy/item/search.api';
    	var _this = this ;
      fetch(URL, {
          method : 'POST',
          mode: 'cors',
          body: JSON.stringify({
          	"where":{
          	   categoryId: [
          	        ["eq",e.target.getAttribute('data-id')]
          	    ],
          	  },
          })
      }).then(res=>{
          if(res.ok){
              res.json().then(data=>{
              		_this.state.proDataOption2=[];
                  for(var k=0; k<data.length; k++){
                  	if(!(data[k].dd)){
                  		_this.state.proDataOption2.push(<li data-id={data[k].id} onClick={(e) => this.inputTClick2_pro(e)}>{data[k].name}</li>)
                  	}
                  }
              })
          }
      })
	}
	inputTClick3(e) {
	    const selectValue = e.target.innerText
	    console.warn(e.target.getAttribute('data-id'));
	    this.setState({
	      optionSelectId3: e.target.getAttribute('data-id')
	    })
	    this.setState({select_show3: "none",giftItem3_productT: selectValue, giftItem3_product:'', giftItem3_type:'' , select_show6: "none", select_show9: "none",  select_show5: "none", select_show8: "none", select_show4: "none", select_show7: "none"})

 	    var URL = ROOTURL_MALL +'kabuy/item/search.api';
     	var _this = this ;
       fetch(URL, {
           method : 'POST',
           mode: 'cors',
           body: JSON.stringify({
           	"where":{
           	   categoryId: [
           	        ["eq",e.target.getAttribute('data-id')]
           	    ],
           	  },
           })
       }).then(res=>{
           if(res.ok){
               res.json().then(data=>{
               		_this.state.proDataOption3=[];
                   for(var k=0; k<data.length; k++){
                   	if(!(data[k].dd)){
                   		_this.state.proDataOption3.push(<li data-id={data[k].id} onClick={(e) => this.inputTClick3_pro(e)}>{data[k].name}</li>)
                   	}
                   }
               })
           }
       })
	}
	inputTClick1_pro(e) {
	    const selectValue = e.target.innerText
	    console.warn(e.target.getAttribute('data-id'));
	    this.setState({
	      giftItem1_productId: e.target.getAttribute('data-id')
	    })
	    this.setState({select_show4: "none",giftItem1_product: selectValue, giftItem1_type:'', select_show7: "none"})
	}
	inputTClick2_pro(e) {
	    const selectValue = e.target.innerText
	    console.warn(e.target.getAttribute('data-id'));
	    this.setState({
	      giftItem2_productId: e.target.getAttribute('data-id')
	    })
	    this.setState({select_show5: "none",giftItem2_product: selectValue, giftItem2_type:'', select_show8: "none"})
	}
	inputTClick3_pro(e) {
	    const selectValue = e.target.innerText
	    console.warn(e.target.getAttribute('data-id'));
	    this.setState({
	      giftItem3_productId: e.target.getAttribute('data-id')
	    })
	    this.setState({select_show6: "none",giftItem3_product: selectValue, giftItem3_type:'' , select_show9: "none"})
	}
	inputTClick1_type(e) {
	    const selectValue = e.target.innerText
	    console.warn(e.target.getAttribute('data-id'));
	    this.setState({
	      giftItem1_typeId: e.target.getAttribute('data-id')
	    })
	    this.setState({select_show7: "none",giftItem1_type: selectValue})
	}
	inputTClick2_type(e) {
	    const selectValue = e.target.innerText
	    console.warn(e.target.getAttribute('data-id'));
	    this.setState({
	      giftItem2_typeId: e.target.getAttribute('data-id')
	    })
	    this.setState({select_show8: "none",giftItem2_type: selectValue})
	}
	inputTClick3_type(e) {
	    const selectValue = e.target.innerText
	    console.warn(e.target.getAttribute('data-id'));
	    this.setState({
	      giftItem3_typeId: e.target.getAttribute('data-id')
	    })
	    this.setState({select_show9: "none",giftItem3_type: selectValue})
	}

	// optionClick(e) {
	//     const selectValue = e.target.innerText
	//     console.warn(e.target.getAttribute('data-id'));
	//     this.setState({
	//       optionSelectId: e.target.getAttribute('data-id')
	//     })
	//     this.setState({select_show: "none", optionBelong: selectValue})
	// }
	handlePostRich(content){
		console.warn(content);
		this.setState({
			richEditor: content
		});
	}

	handleGetInfo(){
		var URL = ROOTURL_MALL + 'kabuy/item/instance.api';
		var _this = this;
		var param = {
			id: this.props.params.id
		};
		fetch(URL,{
		    method: 'POST',
		    mode: "cors",
		    body: JSON.stringify(param)
		}).then(function (res) {
		    	if(res.ok){
		    	    res.json().then(data=>{
		    	        console.log(data);
		    	            _this.setState({
		    	                productName: data.name,
		    	                typeBelong: data.meta.typeName,
		    	                typeSelectId: data.categoryId,
		    	                price: data.price ? data.price.toString() : '0',
		    	                tag: data.tag,
		    	                stock: data.stock,
		    	                imgHash : data.meta.hashed,
		    	                icon : data.meta.icon,
		    	                detailUrl : data.meta.detailUrl,
		    	                initPrice: data.meta.initPrice ? data.meta.initPrice.toString() : '0',
		    	                checkbox1: data.meta.restrict,
		    	                restrictCount: data.meta.restrictCount,
		    	                checkbox2: data.meta.gift,
													ratio: data.meta.GripReward ? data.meta.GripReward.ratio : 0,
													minValue: data.meta.GripReward ? data.meta.GripReward.minValue : 0,
													maxValue: data.meta.GripReward ? data.meta.GripReward.maxValue: 0,
													zitiORwuliu: data.meta.pickupType
		    	            })
		    	            if(data.meta.gifts && data.meta.gifts[0]){
		    	            	_this.setState({
		    	            		giftItem1_productT: data.meta.gifts[0].t_n,
		    	            		giftItem1_product: data.meta.gifts[0].i_n,
		    	            		giftItem1_productId: data.meta.gifts[0].i,
		    	            		giftItem1_type: data.meta.gifts[0].ct_n,
		    	            		giftItem1_typeId:data.meta.gifts[0].ct,
		    	            		giftItem1_count: data.meta.gifts[0].c,
		    	            	})
		    	            }
		    	            if(data.meta.gifts && data.meta.gifts[1]){
		    	            	_this.setState({
		    	            		giftItem2_productT: data.meta.gifts[1].t_n,
		    	            		giftItem2_product: data.meta.gifts[1].i_n,
		    	            		giftItem2_productId: data.meta.gifts[1].i,
		    	            		giftItem2_type: data.meta.gifts[1].ct_n,
		    	            		giftItem2_typeId:data.meta.gifts[1].ct,
		    	            		giftItem2_count: data.meta.gifts[1].c,
		    	            	})
		    	            }
		    	            if(data.meta.gifts && data.meta.gifts[2]){
		    	            	_this.setState({
		    	            		giftItem3_productT: data.meta.gifts[3].t_n,
		    	            		giftItem3_product: data.meta.gifts[3].i_n,
		    	            		giftItem3_productId: data.meta.gifts[3].i,
		    	            		giftItem3_type: data.meta.gifts[3].ct_n,
		    	            		giftItem3_typeId:data.meta.gifts[3].ct,
		    	            		giftItem3_count: data.meta.gifts[3].c,
		    	            	})
		    	            }
		    	        console.log(_this.state)
		    	    })
		    	}
		});
	}

	componentDidMount() {
	    console.log("安装成功");
	}

	handleModify(e){
		this.setState({
			disabled:false,
			submitBtn:'block',
			modifyBtn:'none',
			deleteBtn:'none',
			status:2
		})
	}

	handleSubmit(){
		if(this.state.productName == ''){
			this.setState({errorM: "请输入商品名！"});
		}else if(this.state.typeBelong == ''){
			this.setState({errorM1: "请选择分类！"});
		}
		else{
			var URL = ROOTURL_MALL + 'kabuy/item/instance.api';
			if(this.state.status == 1){
				var restrict = null, restrictCount = null;
				if(this.state.checkbox1 == true){
					restrict = true;
					restrictCount = parseInt(this.state.restrictCount);
				}
				var gift = null, gifts = null;
				if(this.state.checkbox2 == true){
					gift = true;
					gifts = [];
					if(this.state.giftItem1_count>0){
						var obj = { i: this.state.giftItem1_productId, ct: this.state.giftItem1_typeId, c: parseInt(this.state.giftItem1_count), t_n: this.state.giftItem1_productT ,i_n: this.state.giftItem1_product, ct_n: this.state.giftItem1_type   }
						gifts.push(obj);
					}
					if(this.state.giftItem2_count>0){
						var obj = { i: this.state.giftItem2_productId, ct: this.state.giftItem2_typeId, c: parseInt(this.state.giftItem2_count), t_n: this.state.giftItem2_productT ,i_n: this.state.giftItem2_product, ct_n: this.state.giftItem2_type  }
						gifts.push(obj);
					}
					if(this.state.giftItem3_count>0){
						var obj = { i: this.state.giftItem3_productId, ct: this.state.giftItem3_typeId, c: parseInt(this.state.giftItem3_count), t_n: this.state.giftItem3_productT ,i_n: this.state.giftItem3_product, ct_n: this.state.giftItem3_type  }
						gifts.push(obj);
					}
				}
				console.warn('dw1e321e@$%',gifts);
				var param = {
					name: this.state.productName,
					dd: false,
					price:parseFloat(this.state.price),
					category: this.state.typeSelectId,
					tag: this.state.tag,
					stock: this.state.stock,
					meta:{
						typeName: this.state.typeBelong,
						icon: this.state.icon,
						hashed: this.state.imgHash,
						detailUrl: this.state.detailUrl,
						initPrice: parseFloat(this.state.initPrice),
						restrict: restrict,
						restrictCount: restrictCount,
						gift:gift,
						gifts:gifts,
						GripReward: {
							ratio: parseFloat(this.state.ratio),
							minValue: parseFloat(this.state.minValue),
							maxValue: parseFloat(this.state.maxValue)
						},
						pickupType: this.state.zitiORwuliu
					}
				};
				console.log(JSON.stringify(param));

				fetch(URL,{
				    method: 'POST',
				    mode: 'cors',
				    body: JSON.stringify(param)
				}).then(function (res) {
				    if (res.ok){
				    	alert('添加成功！');
				        window.location.href="/MallProductsM";
				    }else{
				        alert('添加失败！可能有重名了！');
				    }
				});
			}else if(this.state.status == 2){
				var restrict = null, restrictCount = null;
				if(this.state.checkbox1 == true){
					restrict = true;
					restrictCount = parseInt(this.state.restrictCount);
				}
				var gift = null, gifts = null;
				if(this.state.checkbox2 == true){
					gift = true;
					gifts = [];
					if(this.state.giftItem1_count>0){
						var obj = { i: this.state.giftItem1_productId, ct: this.state.giftItem1_typeId, c: parseInt(this.state.giftItem1_count), t_n: this.state.giftItem1_productT ,i_n: this.state.giftItem1_product, ct_n: this.state.giftItem1_type   }
						gifts.push(obj);
					}
					if(this.state.giftItem2_count>0){
						var obj = { i: this.state.giftItem2_productId, ct: this.state.giftItem2_typeId, c: parseInt(this.state.giftItem2_count), t_n: this.state.giftItem2_productT ,i_n: this.state.giftItem2_product, ct_n: this.state.giftItem2_type  }
						gifts.push(obj);
					}
					if(this.state.giftItem3_count>0){
						var obj = { i: this.state.giftItem3_productId, ct: this.state.giftItem3_typeId, c: parseInt(this.state.giftItem3_count), t_n: this.state.giftItem3_productT ,i_n: this.state.giftItem3_product, ct_n: this.state.giftItem3_type  }
						gifts.push(obj);
					}
				}
				console.warn('dw1e321e@$%',gifts);
				var param = {
					name: this.state.productName,
					id: this.props.params.id,
					price:parseFloat(this.state.price),
					category: this.state.typeSelectId,
					tag: this.state.tag,
					stock: this.state.stock,
					meta:{
						typeName: this.state.typeBelong,
						icon: this.state.icon,
						hashed: this.state.imgHash,
						detailUrl: this.state.detailUrl,
						initPrice: parseFloat(this.state.initPrice),
						restrict: restrict,
						restrictCount: restrictCount,
						gift: gift,
						gifts: gifts,
						GripReward: {
							ratio: parseFloat(this.state.ratio),
							minValue: parseFloat(this.state.minValue),
							maxValue: parseFloat(this.state.maxValue)
						},
						pickupType: this.state.zitiORwuliu
					}
				};
				console.log(JSON.stringify(param));
				fetch(URL,{
				    method: 'POST',
				    mode: 'cors',
				    body: JSON.stringify(param)
				}).then(function (res) {
				    if (res.ok){
				    	alert('修改成功！');
				        window.location.href="/MallProductsM";
				    }else{
				        alert('修改失败！可能有重名了！');
				    }
				});
			}
		}


	}

	handleDelete(id){
		this.setState({
			delete: !this.state.delete,
			deleteId: id
		})
	}

	// detailText(editorState){
	// 	this.setState({editorState})
	// }

	deleteImg(key) {
	    var newFiles = this.state.imgHash;
	    newFiles.splice(key, 1);
	    this.setState({
	        imgFiles: newFiles
	    })
	}

	//选择优惠券1的商品分类后
	giftItem1proT(val){
		alert(val.target.getAttribute('data-id'))
		this.setState({
			giftItem1_productT: val.target.value
		})

	}
	giftItem2proT(val){
		this.setState({
			giftItem2_productT: val.target.value
		})
	}
	giftItem3proT(val){
		this.setState({
			giftItem3_productT: val.target.value
		})
	}

	deleteType(){
		var _this = this;
		var param = {
		  // id:this.state.deleteId
		}
		   var URL1 = ROOTURL_MALL + 'kabuy/item/instance.api?id=' + this.state.deleteId;
		   fetch(URL1,{
		       method: 'DELETE',
		       mode: "cors",
		       body: param
		   }).then(function (res) {
		       if (res.ok){
		           console.log('delete success');
		           window.location.href="/MallProductsM";
		       }else{
		           console.log(res)
		       }
		   });
		   this.setState({
		       delete: !this.state.delete
		   });
	}

	liziOrti(e){
		const selectValue = e.target.innerText
		console.warn(e.target.getAttribute('data-id'));

		this.setState({select_ztORwl: "none", zitiORwuliu: selectValue})
	}

	render(){
		return (

			<div className="right-wapper" style={{height:'1000px'}}>
			    <div className="rt-wrap">
			        <div className="right-wrap">
			            <div className="wrap" style={{paddingBottom:"40px"}}>
			                <div className={style["input_div"]} style={{margin:'20px 0 20px'}}>
			                    <label>名称</label>
			                    <TextInput inputId="productName"  disabled={this.state.disabled} placeHolder="" val={this.state.productName} onChange={val=>this.setState(Object.assign({}, this.state, {productName: val}))} />&nbsp;&nbsp;
			                     <span style={{marginBottom:'20px',marginLeft:'2px',color:'red'}}>{this.state.errorM}</span>
			                </div>

			                <div className={style["input_div"]} style={{position:'relative'}}>
			                    <label>所属分类</label>
			                    <input inputId="typeBelong" disabled={this.state.disabled} className="default-text" placeholder="" value={this.state.typeBelong} readOnly onFocus={() => this.inputFocus()} onChange={val=>this.setState(Object.assign({},this.state, {typeBelong: val}))}/>&nbsp;&nbsp;
			                    <span style={{marginBottom:'20px',marginLeft:'2px',color:'red'}}>{this.state.errorM1}</span>
			                    <ul  className="input_select" style={{display: this.state.select_show}}>
			                     {this.state.typeData}
			                    </ul>
			                </div>

											<div className={style["input_div"]} style={{position:'relative'}}>
			                    <label>自提/物流</label>
			                    <input inputId="zitiORwuliu" disabled={this.state.disabled} className="default-text" placeholder="" value={this.state.zitiORwuliu} readOnly onFocus={() => this.inputFocusZTORUL()} onChange={val=>this.setState(Object.assign({},this.state, {zitiORwuliu: val}))}/>&nbsp;&nbsp;
			                    <ul  className="input_select" style={{display: this.state.select_ztORwl}}>
			                      <li onClick={(e) => this.liziOrti(e)}>自提</li>
														<li onClick={(e) => this.liziOrti(e)}>物流</li>
			                    </ul>
			                </div>


			                <div className={style["input_div"]} style={{margin:'20px 0 20px'}}>
			                    <label>价格</label>
			                    <TextInput inputId="price"  disabled={this.state.disabled} placeHolder="" val={this.state.price} onChange={val=>this.setState(Object.assign({}, this.state, {price: val}))}/>&nbsp;&nbsp;

			                </div>

			                 <div className={style["input_div"]} style={{margin:'20px 0 20px'}}>
			                    <label>原价</label>
			                    <TextInput inputId="initPrice"  disabled={this.state.disabled} placeHolder="" val={this.state.initPrice} onChange={val=>this.setState(Object.assign({}, this.state, {initPrice: val}))}/>&nbsp;&nbsp;

			                </div>

			                <div className={style["input_div"]} style={{margin:'20px 0 20px'}}>
			                    <label>库存</label>
			                    <TextInput inputId="stock"  disabled={this.state.disabled} placeHolder="" val={this.state.stock} onChange={val=>this.setState(Object.assign({}, this.state, {stock: val}))}/>&nbsp;&nbsp;

			                </div>

											<div className={style["input_div"]} style={{margin:'20px 0 20px'}}>
			                    <label>提成比例</label>
			                    <TextInput inputId="Tichperct"  disabled={this.state.disabled} placeHolder="" val={this.state.ratio} onChange={val=>this.setState(Object.assign({}, this.state, {ratio: val}))}/>&nbsp;&nbsp;

			                </div>

											<div className={style["input_div"]} style={{margin:'20px 0 20px'}}>
			                    <label>最小提成</label>
			                    <TextInput inputId="minTich"  disabled={this.state.disabled} placeHolder="" val={this.state.minValue} onChange={val=>this.setState(Object.assign({}, this.state, {minValue: val}))}/>&nbsp;&nbsp;

			                </div>

											<div className={style["input_div"]} style={{margin:'20px 0 20px'}}>
			                    <label>最大提成</label>
			                    <TextInput inputId="maxTich"  disabled={this.state.disabled} placeHolder="" val={this.state.maxValue} onChange={val=>this.setState(Object.assign({}, this.state, {maxValue: val}))}/>&nbsp;&nbsp;

			                </div>

			                <div className={style["input_div"]} style={{margin:'20px 0 20px'}}>
			                    <label>标签</label>
			                    <TextInput inputId="tag"  disabled={this.state.disabled} placeHolder="" val={this.state.tag} onChange={val=>this.setState(Object.assign({}, this.state, {tag: val}))}/>&nbsp;&nbsp;

			                </div>

			                <div className="checkbox_div" style={{marginTop:'18px',marginBottom:'20px',marginLeft:'50px'}}>
			                    <CheckboxInput id="restrict" disabled={this.state.disabled} isCheck={this.state.checkbox1} onChange={val=>this.setState(Object.assign({}, this.state, {checkbox1: val}))}/>
			                    <label htmlFor="restrict">是否限制数量</label>
			                </div>
			                {this.state.checkbox1 ? <div className={style["input_div"]} style={{margin:'20px 0 20px'}}>
			                    <label>限制数量</label>
			                    <TextInput inputId="restrictCount"  disabled={this.state.disabled} placeHolder="" val={this.state.restrictCount} onChange={val=>this.setState(Object.assign({}, this.state, {restrictCount: val}))}/>&nbsp;&nbsp;
			                </div> : null}

			                 <div className="checkbox_div" style={{marginTop:'18px',marginBottom:'20px',marginLeft:'50px'}}>
			                    <CheckboxInput id="gift" disabled={this.state.disabled} isCheck={this.state.checkbox2} onChange={val=>this.setState(Object.assign({}, this.state, {checkbox2: val}))}/>
			                    <label htmlFor="gift">是否有优惠券</label>
			                </div>
			                {this.state.checkbox2
			                	?	<div>
			                		 <div className={style["input_div"]} >
			                		 		<div style={{position:'relative',float:'left',marginTop:'-2px'}}>
			                		 			<label>优惠券1</label>
			                		 			<input inputId="giftItem1_productT" disabled={this.state.disabled} className="default-text"  value={this.state.giftItem1_productT} readOnly onFocus={() => this.inputFocus1()} onChange={val=>this.setState(Object.assign({},this.state, {giftItem1_productT: val}))} style={{width:'136px !important'}} placeholder="(商品分类)"/>
			                		 			<ul  className="input_select" style={{display: this.state.select_show1,width:'136px !important'}}>
			                		 			 {this.state.typeDataOption1}
			                		 			</ul>
			                		 		</div>
			                		 		<div style={{position:'relative',float:'left'}}>
			                		 			<input inputId="giftItem1_product" disabled={this.state.disabled} className="default-text"  value={this.state.giftItem1_product} readOnly onFocus={() => this.inputFocus4()} onChange={val=>this.setState(Object.assign({},this.state, {giftItem1_product: val}))} style={{width:'200px !important'}} placeholder="(商品名称)"/>
			                		 			<ul  className="input_select" style={{display: this.state.select_show4,width:'200px !important',left:'0'}}>
			                		 			 {this.state.proDataOption1}
			                		 			</ul>
			                		 		</div>
			                		 		<div style={{position:'relative',float:'left'}}>
			                		 			<input inputId="giftItem1_type" disabled={this.state.disabled} className="default-text"  value={this.state.giftItem1_type} readOnly onFocus={() => this.inputFocus7()} onChange={val=>this.setState(Object.assign({},this.state, {giftItem1_type: val}))} style={{width:'160px !important'}} placeholder="(优惠券类型)"/>
			                		 			<ul  className="input_select" style={{display: this.state.select_show7,width:'160px !important',left:'0'}}>
			                		 			 {this.state.giftDataOption1}
			                		 			</ul>
			                		 		</div>
                        			<TextInput inputId="giftItem1_count"  disabled={this.state.disabled} placeHolder="" val={this.state.giftItem1_count} onChange={val=>this.setState(Object.assign({}, this.state, {giftItem1_count: val}))} style={{width:'50px !important'}}/>张&nbsp;&nbsp;
                    			 </div>

                    			 <div className={style["input_div"]} >
			                		 		<div style={{position:'relative',float:'left',marginTop:'-2px'}}>
			                		 			<label>优惠券2</label>
			                		 			<input inputId="giftItem2_productT" disabled={this.state.disabled} className="default-text"  value={this.state.giftItem2_productT} readOnly onFocus={() => this.inputFocus2()} onChange={val=>this.setState(Object.assign({},this.state, {giftItem2_productT: val}))} style={{width:'136px !important'}} placeholder="(商品分类)"/>
			                		 			<ul  className="input_select" style={{display: this.state.select_show2,width:'136px !important'}}>
			                		 			 {this.state.typeDataOption2}
			                		 			</ul>
			                		 		</div>
			                		 		<div style={{position:'relative',float:'left'}}>
			                		 			<input inputId="giftItem2_product" disabled={this.state.disabled} className="default-text"  value={this.state.giftItem2_product} readOnly onFocus={() => this.inputFocus5()} onChange={val=>this.setState(Object.assign({},this.state, {giftItem2_product: val}))} style={{width:'200px !important'}} placeholder="(商品名称)"/>
			                		 			<ul  className="input_select" style={{display: this.state.select_show5,width:'200px !important',left:'0'}}>
			                		 			 {this.state.proDataOption2}
			                		 			</ul>
			                		 		</div>
			                		 		<div style={{position:'relative',float:'left'}}>
			                		 			<input inputId="giftItem2_type" disabled={this.state.disabled} className="default-text"  value={this.state.giftItem2_type} readOnly onFocus={() => this.inputFocus8()} onChange={val=>this.setState(Object.assign({},this.state, {giftItem2_type: val}))} style={{width:'160px !important'}} placeholder="(优惠券类型)"/>
			                		 			<ul  className="input_select" style={{display: this.state.select_show8,width:'160px !important',left:'0'}}>
			                		 			 {this.state.giftDataOption2}
			                		 			</ul>
			                		 		</div>
                        			<TextInput inputId="giftItem2_count"  disabled={this.state.disabled} placeHolder="" val={this.state.giftItem2_count} onChange={val=>this.setState(Object.assign({}, this.state, {giftItem2_count: val}))} style={{width:'50px !important'}}/>张&nbsp;&nbsp;
                    			 </div>

                    			 <div className={style["input_div"]} >
			                		 		<div style={{position:'relative',float:'left',marginTop:'-2px'}}>
			                		 			<label>优惠券3</label>
			                		 			<input inputId="giftItem3_productT" disabled={this.state.disabled} className="default-text"  value={this.state.giftItem3_productT} readOnly onFocus={() => this.inputFocus3()} onChange={val=>this.setState(Object.assign({},this.state, {giftItem3_productT: val}))} style={{width:'136px !important'}} placeholder="(商品分类)"/>
			                		 			<ul  className="input_select" style={{display: this.state.select_show3,width:'136px !important'}}>
			                		 			 {this.state.typeDataOption3}
			                		 			</ul>
			                		 		</div>
			                		 		<div style={{position:'relative',float:'left'}}>
			                		 			<input inputId="giftItem3_product" disabled={this.state.disabled} className="default-text"  value={this.state.giftItem3_product} readOnly onFocus={() => this.inputFocus6()} onChange={val=>this.setState(Object.assign({},this.state, {giftItem3_product: val}))} style={{width:'200px !important'}} placeholder="(商品名称)"/>
			                		 			<ul  className="input_select" style={{display: this.state.select_show6,width:'200px !important',left:'0'}}>
			                		 			 {this.state.proDataOption3}
			                		 			</ul>
			                		 		</div>
			                		 		<div style={{position:'relative',float:'left'}}>
			                		 			<input inputId="giftItem3_type" disabled={this.state.disabled} className="default-text"  value={this.state.giftItem3_type} readOnly onFocus={() => this.inputFocus9()} onChange={val=>this.setState(Object.assign({},this.state, {giftItem3_productT: val}))} style={{width:'160px !important'}} placeholder="(优惠券类型)"/>
			                		 			<ul  className="input_select" style={{display: this.state.select_show9,width:'160px !important',left:'0'}}>
			                		 			 {this.state.giftDataOption3}
			                		 			</ul>
			                		 		</div>
                        			<TextInput inputId="giftItem3_count"  disabled={this.state.disabled} placeHolder="" val={this.state.giftItem3_count} onChange={val=>this.setState(Object.assign({}, this.state, {giftItem3_count: val}))} style={{width:'50px !important'}}/>张&nbsp;&nbsp;
                    			 </div>
	                   		</div>
			                  : null}



			                <div className={style['input_div']}>
			                    <label style={{width:'80px',float:'left'}}>图片</label>
			                    <div style={{width:'316px',float:'left'}}>
			                        <span style={{display:'inline-block'}}>
			                            <img style={{maxWidth: '100px',maxHeight:'100px'}}
			                                 src={!this.state.iconHasChanged && this.state.icon ?
			                                  ROOTURL + 'asset/images/get.api?hashed=' + this.state.icon : this.state.iconPreview}/></span>
			                        <button className={style['main_btn']} disabled={this.state.disabled}
			                                style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3',float:'right'} }
			                                >更换<FileInput disabled={this.state.disabled}
			                            type="file" noMultiple={true}
			                            fileClass={style['imgUploader-btn']}
			                            accept=".jpg,.png,.jpeg,.gif,.bmp"
			                            onChange={(files)=>this.handleIconUpload(files)}/>
			                        </button>
			                    </div>
			                </div>


			                <div className={style["input_div"]} style={{margin:'20px 0 40px'}}>
			                    <label>详情链接</label>
			                  		<TextInput inputId="detailUrl"  disabled={this.state.disabled} placeHolder="" val={this.state.detailUrl} onChange={val=>this.setState(Object.assign({}, this.state, {detailUrl: val}))}/>&nbsp;&nbsp;
			                </div>


			                <span id="hint"/>
			                <button id="submit" className={style["main_btn"]} onClick={this.handlesave.bind(this)}  style={{backgroundColor: '#2285c7',float:'left',border: '1px solid #1e77b3',display: this.state.submitBtn}}>保存</button>
			                <button id="modify" className={style["main_btn"]} style={{backgroundColor: '#2285c7',float:'left',border: '1px solid #1e77b3',display: this.state.modifyBtn,marginLeft:'12px'} } onClick={  (e) => this.handleModify(e) }>修改</button>
			                <button id="delete" className={style["main_btn"]} style={{backgroundColor: '#f2846f',float:'left',border: '1px solid #d55c44',display: this.state.deleteBtn,marginLeft:'12px'} } onClick={ (e) =>this.handleDelete(this.props.params.id) }>删除</button>

			                <Link to={`/MallProductsM`}>
			                     <button id="back" className={style["main_btn"]}  style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3',marginLeft:'12px'}}>返回</button>
			                </Link>
			            </div>
			            <div className="wrap" style={{marginLeft:'0',paddingLeft:'0',height:'300px'}}>

			                <button id="upload" className={style['main_btn']} disabled={this.state.disabled}
			                        style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3'} }>商品轮播图上传 <FileInput
			                    type="file" disabled={this.state.disabled}
			                    fileClass={style['imgUploader-btn']}
			                    accept=".jpg,.png,.jpeg,.gif,.bmp"
			                    onChange={(files)=>this.handleImgUpload(files)}/>
			                </button>
			                <span className={style['tips']} style={{marginLeft:"10px",display:'inline-block'}}>每次上传和删除图片后，请点击上方“保存”按钮进行保存</span>

			                <h3 className='catagory' style={{marginTop:"10px"}}><span className='cata-title'>商品轮播图上传列表</span></h3>
			                <ul id="fileList" className={style['img_list']}>
			                    {this.state.previewImgUrl.length > 0 ? this.state.previewImgUrl.map((img, index)=> {
			                        return <ImageWithState src={img.src} stateMsg={img.msg} id={index} key={index}/>
			                    }) : null}
			                </ul>

			                <h3 className='catagory' style={{marginTop:"10px"}}><span className='cata-title'>商品轮播图列表</span></h3>
			                <ul id="imglist" className={style['img_list']}>
			                    {this.state.imgHash.length > 0 ? this.state.imgHash.map((url, index)=> {
			                        var src = ROOTURL + 'asset/images/get.api?hashed=' + url;
			                        return <ImageWithState onClick={this.deleteImg.bind(this,index)} src={src} id={index} key={index}
			                                               deleteBtn={true}/>

			                    }) : null}
			                </ul>
			            </div>
			        </div>
			    </div>
			    { this.state.delete ?
			      <div id={style.msgDialog}>
			        <div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
			          <div className={style['msgDialog_button']}>
			            <button id={style['msgDialog_yes']} onClick={this.deleteType.bind(this)}>确定</button>
			            <button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
			          </div>
			        </div>
			      </div> : null}
			</div>
		)
	}
}


export default MallProductsEditor
